const bodyParser = require('body-parser')
const express = require('express')
const http = require('http')
const path = require('path')
const co = require('co')
const fs = require('fs')
const app = express()

const wjx = require('./wjx')
const conf = require('./conf')
const EJS = require('./lib/ejs')
const log = require('./lib/log')

app.set('views', path.join(__dirname, 'views'))
app.engine('.html', require('ejs').__express)
app.set('view engine', 'html')
app.locals.EJS = EJS

app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: false }))
app.use(log.reqlog)
app.use(express.static(path.join(__dirname, 'public')))

var obj = parse()

function parse() {
    let file = path.join(__dirname, 'result.json')
    let result = fs.readFileSync(file, { flag: 'r+', encoding: 'utf8' })
    return JSON.parse(result)
}

app.get('/', function(req, res, next) {
    res.render('index', { k: '', arr: obj })
})

app.post('/', function(req, res, next) {
    let k = req.body.k || ''
    let brr = {}
    if (k) {
        for (let i in obj) {
            if (obj[i]['问'].indexOf(k) != -1) {
                brr[i] = obj[i]
            }
        }
    }
    res.render('index', { k: k, arr: brr })
})

app.post('/add', function(req, res, next) {
    co(function*() {
        let url = req.body.url
        url = url.replace('https://', 'http://')
        let ret = yield wjx.query(url)
        let _obj = parse()
        for (let j in ret) {
            console.log(`第${ret[j].topic}题`)
            _obj[ret[j].topic] = { '问': ret[j].question, '答': ret[j].answer }
        }
        fs.writeFileSync('result.json', JSON.stringify(_obj, null, 2))
        obj = _obj
        res.redirect('/')
    }).catch(function(err) {
        next(err)
    })
})

app.use(function(req, res, next) {
    res.status(404).send('404 Not Found')
})

app.use(function(err, req, res, next) {
    log(err.stack)
    res.status(500).send('500 Server Error')
})

const server = http.createServer(app)
server.on('error', function(err) {
    log(err)
}).on('listening', function() {
    log('Listening on ' + server.address().port)
}).listen(conf.port)